﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Higgs.AutoSync.Startup
{
    class Program
    {
        static readonly Mutex mutex = new Mutex(true, "{5350c52a-1fc6-405f-9808-4887df0fdc71}");
        private static NotifyIcon icon;
        private static Process configProcess;

        static void Main(string[] args)
        {
            if (!mutex.WaitOne(TimeSpan.Zero, false))
            {
                MessageBox.Show("Another instance of the app is currently running. Please OK to exit.", Resource.ProgramName,
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
                return;
            }

            mutex.ReleaseMutex();

            CreateNotifyIcon();
            MinimizeFootprint();

            Application.Run();
        }

        static void CreateNotifyIcon()
        {
            var menu = new ContextMenu();
            var mStatus = new MenuItem("Start");
            var mConfig = new MenuItem("Config");
            var mExit = new MenuItem("Exit");

            mStatus.Click += OnStatusClick;
            mConfig.Click += OnConfigClick;
            mExit.Click += OnApplicationExit;

            menu.MenuItems.Add(mStatus);
            menu.MenuItems.Add(mConfig);
            menu.MenuItems.Add(new MenuItem("-"));
            menu.MenuItems.Add(mExit);

            icon = new NotifyIcon
            {
                Icon = Resource.favicon,
                ContextMenu = menu,
                Text = Resource.ProgramName,
                Visible = true
            };
        }

        private static void OnStatusClick(object sender, EventArgs e)
        {
            var processor = new SyncProcessor();
            processor.Start();
        }

        private static void OnConfigClick(object sender, EventArgs e)
        {
            var configAppName = ConfigurationManager.AppSettings["configAppName"];
            var p = new ProcessStartInfo(configAppName);

            configProcess = Process.Start(p);
        }

        private static void OnApplicationExit(object sender, EventArgs e)
        {
            icon.Dispose();

            if(configProcess != null && !configProcess.HasExited) configProcess.Kill();
            
            Trace.Flush();
            Trace.Close();
            Application.Exit();
        }

        [DllImport("psapi.dll")]
        static extern int EmptyWorkingSet(IntPtr hwProc);

        static void MinimizeFootprint()
        {
            EmptyWorkingSet(Process.GetCurrentProcess().Handle);
        }

        public static MenuItem mExit { get; set; }
    }
}
